package com.chuanyang.driverh.mainmy;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.amap.LocationEntity;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.mainmy.adapter.AddressAdapter;
import com.chuanyang.driverh.sqlite.DBHistoryAddressContext;
import com.chuanyang.driverh.utils.ActivityUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.LogUtils;
import com.chuanyang.driverh.utils.PermissoinUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.eventbus.AddAddrEvent;
import com.chuanyang.driverh.utils.eventbus.EventBusUtil;

import java.util.ArrayList;
import java.util.List;


public class AddAddrActivity extends BaseTitleActivity implements PoiSearch.OnPoiSearchListener  {
    private TextView tv_city;
    private EditText et_addr;
    private TextView tv_cancel;
    private ListView lv_addr_his;
    private ListView lv_addr;
    private PoiResult poiResult; // poi返回的结果
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索
    private AddressAdapter addrAdapter;//搜索结果、
    private AddressAdapter addrHisAdapter;//历史搜索。

    private String city;
    private String city_id;

    private List<LocationEntity> list;
    private List<LocationEntity> listHis;
    private DBHistoryAddressContext save;
    private View header;
    private View footer;

    private int type;////1,个人信息中选择地址，2，添加线路起始地，3，添加线路终点。

    @Override
    protected int getContentResId() {
        return R.layout.my_act_input_addr;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        LogUtils.d("initViewStart",System.currentTimeMillis()+"");
        setBackImg();
        tv_city = (TextView) findViewById(R.id.tv_city);
        et_addr = (EditText) findViewById(R.id.et_addr);
        tv_cancel = (TextView) findViewById(R.id.tv_cancel);
        lv_addr_his = (ListView) findViewById(R.id.lv_addr_his);
        lv_addr = (ListView) findViewById(R.id.lv_addr);
    }

    @Override
    protected void initData() {
        LogUtils.d("initDataStart",System.currentTimeMillis()+"");
        type=getIntent().getIntExtra("type",1);
        checkPermission();
        getTitleTextView().setText("输入地址");
        save = new DBHistoryAddressContext(activityContext);
        city = StringUtil.isBlank(SharedPrefUtil.getCity()) ? "上海" : SharedPrefUtil.getCity();
        tv_city.setText(city);


        listHis = save.getHistoryAddressList();
        header = View.inflate(activityContext, R.layout.item_textview_left, null);
        ((TextView) header.findViewById(R.id.tv_content)).setText("历史搜索");
        footer = View.inflate(activityContext, R.layout.item_text, null);
        ((TextView) footer.findViewById(R.id.tv_item)).setText(listHis.size()==0?"无搜索历史":"清空历史搜索");
     /*   footer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save.deleteall();
                addrAdapter.clear();
            }
        });*/
        lv_addr_his.addHeaderView(header);
        lv_addr_his.addFooterView(footer);

        addrHisAdapter = new AddressAdapter(activityContext, listHis);

        lv_addr_his.setAdapter(addrHisAdapter);
        lv_addr_his.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0 ) {
                    return;
                }else if (position == addrHisAdapter.getCount()+1){
                    save.deleteall();
                    addrHisAdapter.clear();
                    ((TextView) footer.findViewById(R.id.tv_item)).setText("无搜索历史");
                    return;
                }


                LocationEntity entity = (LocationEntity) addrHisAdapter.getItem(position - 1);
//                save.insert(entity);
                EventBusUtil.postEvent(new AddAddrEvent(entity,type));
                finish();
            }
        });

        list=new ArrayList<LocationEntity>();
        addrAdapter = new AddressAdapter(activityContext, list);
        lv_addr.setAdapter(addrAdapter);
        lv_addr.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LocationEntity entity = (LocationEntity) addrAdapter.getItem(position);
                save.insert(entity);
                EventBusUtil.postEvent(new AddAddrEvent(entity,type));
                finish();
            }
        });

    }

    @Override
    protected void initListener() {
        LogUtils.d("listnerStart",System.currentTimeMillis()+"");
        tv_city.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);

        et_addr.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                addrAdapter.clear();
                String newText = s.toString().trim();
                if (!StringUtil.isBlank(s.toString())) {
                    query = new PoiSearch.Query(newText, "", tv_city.getText().toString());// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
                    query.setPageSize(15);// 设置每页最多返回多少条poiitem
                    query.setPageNum(0);// 设置查第一页
                    poiSearch = new PoiSearch(activityContext, query);
                    poiSearch.setOnPoiSearchListener(AddAddrActivity.this);
                    poiSearch.searchPOIAsyn();

                    lv_addr_his.setVisibility(View.GONE);
                    lv_addr.setVisibility(View.VISIBLE);

                } else {
//                    List<LocationEntity> list = save.getHistoryAddressList();
//                    if (list.size() > 0) addrAdapter.add(list);

                    lv_addr_his.setVisibility(View.VISIBLE);
                    lv_addr.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
           }
        });
//        AMapUtil.startOnceLocation(activityContext,this);//开启一次定位，拿到城市。
        LogUtils.d("listnerEnd",System.currentTimeMillis()+"");
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        LogUtils.d("onPoiSearched",System.currentTimeMillis()+"");
        if (rCode == 1000) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    // 取得搜索到的poiitems有多少页
                    List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    if (poiItems.size() != 0) {

                        setAdapter(poiItems);
                    }
                }
            } else {
                PrintUtil.toast(activityContext, "无搜索结果");
            }
        }

    }
    public void setAdapter(List<PoiItem> data) {
        LogUtils.d("setAdapter",System.currentTimeMillis()+"");
        List<LocationEntity> temp = new ArrayList<LocationEntity>();
        LocationEntity item = null;
        PoiItem poi = null;
        for (int i = 0; i < data.size(); i++) {
            poi = data.get(i);
            item = new LocationEntity();
            item.setProvince(poi.getProvinceName());
            city = poi.getCityName();
            item.setCity(StringUtil.isBlank(city)?poi.getProvinceName():city);
            item.setRegion_name(poi.getAdName());
            item.setDistrict(poi.getAdName());
            item.setBuilding(poi.getTitle());
//            item.setCity_id(city_id);
            //地址描述可能为空(新的api 地址描述不返回空了)
            item.setAddress(TextUtils.isEmpty(poi.getSnippet()) ? getPCDStr(poi) : poi.getSnippet());
            item.setLongitude(poi.getLatLonPoint().getLongitude());
            item.setLatitude(poi.getLatLonPoint().getLatitude());
            temp.add(item);
        }
        addrAdapter.add(temp);
    }
    public String getPCDStr(PoiItem poi) {
        LogUtils.d("getPCDStr",System.currentTimeMillis()+"");
        if (poi.getCityName().equals(poi.getProvinceName())) {
            return poi.getProvinceName() + poi.getAdName();
        } else {
            return poi.getProvinceName() + poi.getCityName() + poi.getAdName();
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {
        LogUtils.d("onPoiItemSearched",System.currentTimeMillis()+"");
    }


 /*   public void onEventMainThread(CitySelectEvent event) {
//        String[] temp = event.getCity().split("-");
        tv_city.setText(event.getCity());
    }*/

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_city:
                DialogUtil.cityPick(activityContext,tv_city);
//                cityPick(tv_city);
//                ActivityUtil.startActivity(activityContext, SelectCityActivity.class);
                break;
            case R.id.tv_cancel:
                ActivityUtil.startActivity(activityContext,new Intent(activityContext, SelectAddrAsMapActivity.class).putExtra("type",type));
                finish();
                break;
        }
    }
/*
    public void cityPick(final TextView view) {
        AddressPickTask task = new AddressPickTask(this);
        task.setHideCounty(true);
        task.setCallback(new AddressPickTask.Callback() {
            @Override
            public void onAddressInitFailed() {
                PrintUtil.toast(activityContext,"数据初始化失败");
            }

            @Override
            public void onAddressPicked(Province province, City city, County county) {
                view.setText(city.getAreaName());
//                showToast(province.getAreaName() + " " + city.getAreaName());
            }
        });
        task.execute("山东", "日照");
    }*/
/*
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        LogUtils.d("onLocationChanged",System.currentTimeMillis()+"");
        String city=aMapLocation.getCity();
        if (!StringUtil.isBlank(city)){
            tv_city.setText(city);
            SharedPrefUtil.setCity(city);
        }
    }*/



    private void checkPermission() {
        LogUtils.d("checkPermission",System.currentTimeMillis()+"");
        String[] perms = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (PermissoinUtil.checkAndRequestPermissions(activityContext,perms)){


        }else{
            PrintUtil.toast(activityContext,"请给应用定位的权限");
        }

        LogUtils.d("checkPermissioEnd",System.currentTimeMillis()+"");
    }
}
